const app = getApp();
import { queryDealerByCityNameAndCarSeriesId, postAskPrice, getCarStyle, getCitysList, decrypt, addWxUser,getOneId,getOpenId,getWxUser } from './../../../server/api'
Page({
  data: {
    oss_url: app.globalData.oss_url,
    ossUrl: '',
    city: app.globalData.city,
    rightIcon: '',
    white: '#fff',
    activeIndex: 0,
    userData: {},
    citys: [],
    saleCarTitle: '',
    countryIndex: 0,
    genterIndex: 0,
    reject: 0,
    customerName: '',
    phone: '',
    show: false,
    sex: '先生',
    countryCodeIndex: '',
    dealerResult: '',
    dealers:[],
    dealerList: [],
    nowSaleCarsData: [],
    genter: [{ sex: '先生' }, {sex: '女士'}],
    navigation_show: true,
    dealer_id: 0,
    makeId:'',
    makeName:"",
    styleYear:''
  },
  onLoad: function (options) {
  // console.log(options)
    this.setData({
      rightIcon: this.data.oss_url + '/right-icon.png',
      ossUrl: options.ossUrl,
      modelId: options.modelId,
      phone: app.globalData.user_info.phone,
      oneId: app.globalData.user_info.oneId,
      makeId:options.makeId,
      makeName:options.makeName,
      modelName:options.modelName,
      styleName:options.styleName,
      styleYear:options.styleYear
    });
    let data = {
      modelId: options.modelId
    }
    if(options.dealer_id){
      this.setData({
        dealer_id:options.dealer_id,
        dealerResult:options.dealer_id
      })
    }
    this.getCarStyleData(data);
    this.cityData()
  },
  onShow: function () {
    this.setData({ city: app.globalData.city, })
    this.getDealersList();
  },
  to_address() {
    wx.navigateTo({
      url: '/pages/main/chooseACity/index',
    })
  },
  to_agreement() {
    wx.navigateTo({
      url: '/pages/mine/agreement/index',
    })
  },
  getDealersList() {
    let data = {
      carSeriesId: this.data.modelId,
      cityName: this.data.city,
      makeId:this.data.makeId
    }
    queryDealerByCityNameAndCarSeriesId(data).then(res => {
      if (res.code == 0) {
        let list = res.data;
        for (let i = 0; i < list.length; i++) {
          if(this.data.dealer_id == 0 ){
            if(i < 3){
              list[i]['checked'] = true
              this.data.dealers.push(list[i]['deptId'])
              this.setData({
                dealerResult:this.data.dealers
              })
            }
             else{
              list[i]['checked'] = false
            }
          }
        }
        this.setData({
          dealerList: res.data
        })
      }
    })
  },
  getCarStyleData(data) {
    getCarStyle(data).then(res => {
      if (res.code == 0) {
        this.setData({
          nowSaleCarsData: res.data
        })
      }
    })
  },
  showSaleCars() {
    this.setData({
      show: true
    })
  },
  hideOverlay() {
    this.setData({
      show: false
    })
  },
  form_phone_change(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  getName(e) {

    this.setData({
      customerName: e.detail.value
    })
  },
  get_phone(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let obj = {}
      obj['openId'] = app.globalData.user_info.openId
      obj['session_key'] = app.globalData.session_key
      obj['encryptedData'] = e.detail.encryptedData
      obj['iv'] = e.detail.iv
      decrypt(obj).then(res => {
       
        if (res.code == 0) {
          app.globalData.user_info.phone = res.data.phone
          this.setData({ phone: app.globalData.user_info.phone })
          let obj_phone = {}
          obj_phone['openId'] = app.globalData.user_info.openId
          obj_phone['phone'] = app.globalData.user_info.phone
          addWxUser(obj_phone).then(res_phone => {
          })
        }
      })
    } else {
      this.setData({ reject: 1 })
    }
  },
  get_openid() {
    wx.login({
      success(res) {

        if (res.code) {
          let obj = {}
          obj['jsCode'] = res.code
          getOpenId(obj).then(res_openid => {
            if (res_openid.code == 0) {
              app.globalData.user_info.openid = res_openid.data.openid
              let obj = {}
              obj['openId'] = app.globalData.user_info.openid
              getWxUser(obj).then(res_user => {
                if (res_user.data) {
                  app.globalData.user_info.avatarUrl = res_user.data.avatarUrl
                  app.globalData.user_info.nickName = res_user.data.nickName
                  app.globalData.user_info.openId = res_user.data.openId
                  app.globalData.user_info.phone = res_user.data.phone
                }
              })

              getOneId(obj).then(res => {
                if (res.code == 0) {
                  app.globalData.user_info.oneId = res.data
                }
              })
            }
          })
        }
      }
    })
  },
  formValidate() {
    //  let dealerId='';
    if (this.data.customerName == '') {
      wx.showToast({
        title: '请填写您的称呼',
        icon: 'none',
        duration: 1500
      })
      return
    }
    if (!this.check_phone(this.data.phone)) {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none',
        duration: 1500
      })
      return
    }

    if (this.data.dealerResult == '') {
      wx.showToast({
        title: '请选择经销商',
        icon: 'none',
        duration: 1500
      })
      return
    }
    let dealerId =this.data.dealerResult.toString();
      
    let data = {
      oneId: this.data.oneId,
      sex: this.data.sex=='先生'?'male':'female',
      customerName: this.data.customerName,
      mobile: this.data.phone,
      city: this.data.city,
      dealerIds: dealerId,
      intentCarStyle: this.data.styleName,
      intentCarModel:this.data.modelName,
      client: 'program',
      firstChannelName:'客户端',
      secondChannelName:'小程序',
      intentCarBrand:this.data.makeName,
    }
    postAskPrice(data).then(res => {
      if (res.code == 0) {
        wx.showToast({
          title: '已请求询价，稍后会有销售顾问联系您',
          icon: 'none',
          duration: 1500
        })
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)

      } else {
        wx.showToast({
          title: res.errMsg,
          icon: 'none',
          duration: 1500
        })
      }
    })
  },
  onPageScroll: function (e) {
    if (e.scrollTop >= 30) {
      this.setData({
        navigation_show: false
      })
    } else {
      this.setData({
        navigation_show: true
      })
    }
  },
  genterSelect(e) {
    this.setData({
      activeIndex: e.currentTarget.dataset.index,
      sex: e.currentTarget.dataset.sex
    })
  },
  bindCountryChange(e) {
    this.setData({
      city: this.data.citys[e.detail.value]
    })
  },
  check_phone(phone) {
    let reg = new RegExp("^[1][3,4,5,7,8][0-9]{9}$");
    return reg.test(phone)
  },
  checkboxChange(event) {
    let arr = this.data.dealerList
    let sum = 0
    for (let i = 0; i < arr.length; i++) {
      if (event.detail.value.indexOf(arr[i]['deptId'].toString()) > -1) {
        sum++
      }
    }
    if (sum <= 5) {
      for (let i = 0; i < arr.length; i++) {
        if (event.detail.value.indexOf(arr[i]['deptId'].toString()) > -1) {
          arr[i]['checked'] = true
        }
        else {
          arr[i]['checked'] = false
        }
      }
    }
    if (sum > 5) {
      wx.showToast({
        title: '最多选择5家经销商',
        icon: 'none',
        duration: 1000
      })
    }
    this.setData({
      dealerResult: event.detail.value,
      dealerList: arr
    });
  },
  askPrice(e) {
    let {modelname, stylename } = e.currentTarget.dataset;
    this.setData({
     modelName:modelname,
     styleName:stylename
    })
    let that = this;
    that.onLoad();
  },
  cityData() {
    getCitysList().then(res => {
      if (res.code == 0) {
        let arr = []
        for (let i = 0; i < res.data.length; i++) {
          for (let j = 0; j < res.data[i]['city'].length; j++) {
            arr.push(res.data[i]['city'][j]['nameCity'])
          }
        }
        this.setData({
          citys: arr
        })
      }
    })
  }
})
